package cn.gov.ssxmzj.service;

import cn.gov.ssxmzj.entry.OptionInfo;
import cn.gov.ssxmzj.entry.Result;
import cn.gov.ssxmzj.mapper.OptionMapper;
import cn.gov.ssxmzj.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OptionService {

    @Autowired
    private OptionMapper optMapper;

    public Result getOptionsByServiceType(String serviceType){
        Map sqlMap = Utils.asMap("serviceType",serviceType,"validTag","1");
        List<Map> optionInfos = optMapper.getOptionInfoByService(sqlMap);
        if(Utils.isEmpty(optionInfos)){
            return new Result(Result.SERVICE_ERROR,"暂无该类型数据","");
        }
        List<Map> ret = new ArrayList<Map>();
        List<Map> options = new ArrayList<Map>();
        Map serviceMap = new HashMap();
        serviceMap = Utils.asMap("service_id",optionInfos.get(0).get("SERVICE_ID"),
                "service_name",optionInfos.get(0).get("SERVICE_NAME"));
        for(Map optionInfo:optionInfos){

            if(!optionInfo.get("SERVICE_ID").equals(serviceMap.get("service_id"))){
                //是新的service
                serviceMap.put("optionInfo",options);
                ret.add(serviceMap);
                //创建新的service
                serviceMap = Utils.asMap("service_id",optionInfo.get("SERVICE_ID"),
                        "service_name",optionInfo.get("SERVICE_NAME"));
                options = new ArrayList<Map>();
            }
            //不是新的service,则拼装option节点
            options.add(Utils.asMap("option_id",optionInfo.get("OPTION_ID"),
                    "option_name",optionInfo.get("OPTION_NAME")));
        }
        if(!Utils.isEmpty(options)){
            serviceMap.put("optionInfo",options);
            ret.add(serviceMap);
        }
        Map retMap = Utils.asMap("serviceInfo",ret);
        return new Result(Result.SUCCESS,"查询成功",retMap);
    }

    /**
     * 根据id获取option的信息
     * @param optionId
     * @param serviceId
     * @return
     */
    public Result getOptionInfo(String optionId ,String serviceId){
        Map sqlMap = Utils.asMap("optionId",optionId,"serviceId",serviceId,"validTag","1");
        List<Map> optionInfo = optMapper.getOptionInfoById(sqlMap);
        if(Utils.isEmpty(optionInfo)){
            return new Result(Result.SERVICE_ERROR,"未获取到要查询的内容,请刷新页面重试","");
        }
        Map option = optionInfo.get(0);
        String html = "<h1>"+option.get("OPTION_NAME")+"</h1></br>"+option.get("SERVICE_CONTENT")+
                "</br>"+option.get("OPTION_CONTENT");
        return new Result(Result.SUCCESS,"查询成功",html);
    }
}
